package com.lingo.mgr.service.impl;

import com.lingo.mgr.enums.OpenAiEnum;
import com.lingo.mgr.interceptor.InvalidKeyOpenAiAuthInterceptor;
import com.lingo.mgr.mapper.GptApiKeyConfigMapper;
import com.lingo.mgr.service.LlmCacheService;
import com.lingo.mgr.service.OpenAiService;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.function.KeyRandomStrategy;
import lombok.RequiredArgsConstructor;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author PC
 */
@Service
@RequiredArgsConstructor
public class OpenAiServiceImpl implements OpenAiService {


    private final LlmCacheService llmCacheService;

    private final GptApiKeyConfigMapper chatApiKeyConfigMapper;


    @Value("${openai.apiHost}")
    private String apiHost;

    @Override
    public OpenAiClient getOpenAiClient(Integer llmVersion) {
        List<String> apiKeys = llmCacheService.getGptApiKeyConfigs(llmVersion);
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.connectTimeout(30, TimeUnit.SECONDS);
        client.writeTimeout(30, TimeUnit.SECONDS);
        client.readTimeout(30, TimeUnit.SECONDS);
        OkHttpClient httpClient = client.build();
        return OpenAiClient.builder()
            .apiKey(apiKeys)
            .authInterceptor(new InvalidKeyOpenAiAuthInterceptor(chatApiKeyConfigMapper,llmCacheService))
            .okHttpClient(httpClient)
            .apiHost(apiHost)
            .keyStrategy(new KeyRandomStrategy())
            .build();
    }


    @Override
    public OpenAiStreamClient getOpenAiStreamClient(Integer llmVersion) {
        List<String> apiKeys = llmCacheService.getGptApiKeyConfigs(llmVersion);
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.connectTimeout(30, TimeUnit.SECONDS);
        client.writeTimeout(30, TimeUnit.SECONDS);
        client.readTimeout(30, TimeUnit.SECONDS);
        OkHttpClient httpClient = client.build();
        return OpenAiStreamClient.builder()
            .apiKey(apiKeys)
            .authInterceptor(new InvalidKeyOpenAiAuthInterceptor(chatApiKeyConfigMapper,llmCacheService))
            .okHttpClient(httpClient)
            .apiHost(apiHost)
            .keyStrategy(new KeyRandomStrategy())
            .build();
    }
}
